package com.ajieee.merge.util;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author ajieee
 * @date 2025-10-02
 */
public class DateUtils {

	public static LocalDate parseDate(Object src, String pattern) {
		if (src instanceof String s) {
			return LocalDate.parse(s, Formatter.get(pattern));
		} else if (src instanceof Integer i) {
			return LocalDate.parse(i.toString(), Formatter.get(pattern));
		} else {
			throw new IllegalArgumentException("parseDate 仅支持String、Integer类型");
		}
	}

	public static <T> T formatDate(LocalDate date, String pattern, Class<T> targetClass) {
		if (date == null) {
			return null;
		}
		String format = date.format(Formatter.get(pattern));
		if (targetClass == String.class) {
			return targetClass.cast(format);
		} else if (targetClass == Integer.class) {
			return targetClass.cast(Integer.parseInt(format));
		}
		return targetClass.cast(format);
	}

	public static class Formatter {

		private static final Map<String, DateTimeFormatter> cache = new ConcurrentHashMap<>();

		static {
			cache.put("yyyy-MM-dd", DateTimeFormatter.ofPattern("yyyy-MM-dd"));
			cache.put("yyyyMMdd", DateTimeFormatter.ofPattern("yyyyMMdd"));
		}

		public static DateTimeFormatter get(String pattern) {
			return cache.computeIfAbsent(pattern, DateTimeFormatter::ofPattern);
		}

	}

}
